<?php

function _ctlMenu($name, $attribs)
{
	$cacheId = 'WebControl.adminMenu.' . $name;
	if (defined('DEPLOY_MODE') && DEPLOY_MODE) {
	    $lifetime = 900;
	} else {
	    $lifetime = 0;
	}
	$rowset = FLEA::getCache($cacheId, $lifetime);
	if (!$rowset) {
		$tableMenus =& FLEA::getSingleton('Model_Menus');
		/* @var $tableSysMenu Table_SysMenu */
		$rowset = $tableMenus->findAll('menu_display = 1', 'parent_id ASC, menu_order ASC');
		FLEA::writeCache($cacheId, $rowset);
	}

	/**
	 * 转换为树形结构
	 */
	FLEA::loadHelper('Array');
	$menu = array_to_tree($rowset, 'menu_id', 'parent_id', 'submenu');

	$controller = $_GET['controller'];
	$action = $_GET['action'];

	$current_id = 0;

	///<ul id="dashmenu">
	//	<li><a href="{ url controller='admin' action='manager' }" class="current">测试</a></li>
	//</ul>

	$output = "<ul id=\"adminmenu\">\n";
	
	/* 根据controller和action查找菜单ID*/
	$conditions = 'menu_controller = \''.$controller.' \' AND menu_action = \''.$action.'\'';
	$singelMenu = $tableMenus->find($conditions);

	foreach ( $menu as $key => $item ) {		
		
		$class = '';
		
		if ( (strcmp($item[menu_controller],$controller) == 0) && (strcmp($item[menu_action],$action) == 0) ){
				//|| ($item[menu_id] == $item[submenu][parent_id])) {
			$class = ' class="current"';
			$current_id = $item[menu_id];
		}		
		if (isset($item[submenu])) {
			foreach ( $item[submenu] as $subkey => $subitem ) {				
				if ( $subitem[parent_id] == $singelMenu[parent_id] )  {
					$class = ' class="current"';
				}
			}
		}
		$output .= "<li><a href=\"".url($item[menu_controller],$item[menu_action])."\"". $class.">".$item[menu_name]."</a></li>\n";
		
	}	
	$output .= "</ul>\n";
	
	/*显示子菜单*/
	$output .= "<ul id=\"submenu\">\n";
	foreach ( $menu as $key => $item ) {	
		if (isset($item[submenu])) {
			foreach ( $item[submenu] as $subkey => $subitem ) {	
				$class = '';
				if ( (strcmp($subitem[menu_controller],$controller) == 0) && (strcmp($subitem[menu_action],$action) == 0) ) $class = ' class="current"';

				if ( ($subitem[parent_id] == $current_id) || ($subitem[parent_id] == $singelMenu[parent_id]) )  {
					$output .= "<li><a href=\"".url($subitem[menu_controller],$subitem[menu_action])."\"". $class.">".$subitem[menu_name]."</a></li>\n";
				}
			}
		}
	}	
	$output .= "</ul>\n";

	$output .= "<ul id=\"dashmenu\">\n";
	//$output .= "<li><a href=\"\" class=\"current\">".$singelMenu[menu_name]."</a></li>\n";
	$output .= "<li><a href=\"\" >".$singelMenu[menu_name]."</a></li>\n";
	$output .= "</ul>\n";
	return $output;

	
}